# -*- coding: utf-8  -*-
#
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from waveapi import events
from waveapi import model
from waveapi import robot
from waveapi import util
from waveapi import robot_abstract
from waveapi import document
import logging

def On_My_Robots(event, context):
  """Invoked when any participants have been added/removed."""
  added = event.properties['participantsAdded']
  Removed = event.properties['participantsRemoved']
  for p in Removed:
      if p == "my-robots@appspot.com":
           root_wavelet = context.GetRootWavelet()
           if event.modifiedBy != root_wavelet.GetCreator():
              root_wavelet.AddParticipant("my-robots@appspot.com")
  for p in added:
      if p == "secure-wave-preview@appspot.com":
           context.GetRootWavelet().AddParticipant("my-robots@appspot.com")
def OnDOCUMENT_CHANGED(event, context):
  blip = context.GetBlipById(event.properties["blipId"])
  if blip.GetCreator() == event.modifiedBy:
     blipDoc = blip.GetDocument()
     text = blipDoc.GetText()
     match = text.find(':secure-wave;')
     if match > -1:
         blipDoc.DeleteRange(document.Range(match, match+13))
         blipDoc.InsertElement(match, document.Gadget('http://secure-wave-preview.appspot.com/secure-wave.xml'))
if __name__ == '__main__':
  myRobot = robot.Robot('secure-wave-preview', 
      image_url='http://secure-wave-preview.appspot.com/icon.png',
      version='1.05',
      profile_url='http://secure-wave-preview.appspot.com/about.html')
  myRobot.RegisterHandler(events.WAVELET_PARTICIPANTS_CHANGED, On_My_Robots)
  myRobot.RegisterHandler(events.DOCUMENT_CHANGED, OnDOCUMENT_CHANGED)
  myRobot.Run()